<!-- pages/order/detail.vue -->
<template>
  <view class="page-container">
    <!-- 顶部核销信息 -->
    <view class="section verification-section">
      <view class="verification-code">
        <text class="code-text">{{ orderInfo.verificationCode }}</text>
        <text class="code-label">核销码</text>
      </view>
      <view class="car-model">
        <uni-icons type="car" size="24" color="#666" />
        <text>{{ vehicleTypeLabel }} | {{ vehicleModelLabel }}</text>
        <text class="license-plate">{{ orderInfo.vehicle?.licensePlate }}</text>
      </view>
    </view>

    <!-- 服务内容 -->
    <view class="section service-section">
      <view class="section-title">服务内容</view>
      <view 
        v-for="(item, index) in orderInfo.services" 
        :key="index"
        class="service-item"
      >
        <text class="service-name">{{ item.name }}</text>
        <text class="service-price">¥{{ item.price.toFixed(2) }}</text>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="section info-section">
      <view class="section-title">订单信息</view>
      <view class="info-item">
        <text>原价</text>
        <text>¥{{ orderInfo.originalPrice.toFixed(2) }}</text>
      </view>
      <view class="info-item">
        <text>优惠</text>
        <text class="discount">-¥{{ orderInfo.discount.toFixed(2) }}</text>
      </view>
      <view class="info-item total">
        <text>实付金额</text>
        <text class="amount">¥{{ orderInfo.paymentAmount.toFixed(2) }}</text>
      </view>
      <view class="info-item">
        <text>订单编号</text>
        <text class="order-id">{{ orderInfo.orderNumber }}</text>
      </view>
      <view class="info-item">
        <text>预约时间</text>
        <text>{{ formatTime(orderInfo.reserveTime) }}</text>
      </view>
      <view class="info-item">
        <text>支付时间</text>
        <text>{{ formatTime(orderInfo.payTime) }}</text>
      </view>
      <view v-if="orderInfo.verificationStatus" class="info-item">
        <text>核销时间</text>
        <text>{{ formatTime(orderInfo.verifyTime) }}</text>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="footer">
      <button 
        class="verify-btn"
        :class="{ verified: orderInfo.verificationStatus }"
        :disabled="orderInfo.verificationStatus"
        @tap="handleVerification"
      >
        {{ orderInfo.verificationStatus ? '已核销' : '确认核销' }}
      </button>
    </view>

    <!-- 核销确认弹窗 -->
    <uni-popup ref="verifyPopup" type="dialog">
      <uni-popup-dialog 
        type="warning"
        title="操作确认"
        content="请仔细核对订单信息，此操作不可撤销！"
        @confirm="confirmVerification"
        @close="cancelVerification"
      />
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import request from '../../utils/request'

// 字典数据
const carTypeDict = ref([])
const carModelDict = ref([])
const sysVerification = ref([])

// 订单数据模型
const orderInfo = reactive({
  orderId: null,
  verificationCode: '',
  vehicle: {},
  verificationCode: '',
  vehicle: {},
  services: [],
  originalPrice: 0,
  discount: 0,
  paymentAmount: 0,
  orderNumber: '',
  reserveTime: null,
  payTime: null,
  verificationStatus: false,
  verifyTime: null,
  ext2: 0 // 核销状态字典值
})

// 计算车辆类型标签
const vehicleTypeLabel = computed(() => {
  return carTypeDict.value.find(item => item.value === orderInfo.vehicle?.vehicleType)?.label || '未知类型'
})

// 计算车辆型号标签
const vehicleModelLabel = computed(() => {
  return carModelDict.value.find(item => item.value === orderInfo.vehicle?.vehicleModel)?.label || '未知型号'
})

// 加载字典数据
const loadDictData = async () => {
  try {
    const [typeRes, modelRes] = await Promise.all([
      request({ url: '/system/dict/data/type/car_type', method: 'get' }),
      request({ url: '/system/dict/data/type/car_model', method: 'get' }),
	  request({ url: '/system/dict/data/type/sys_verification', method: 'get' })
    ])

    if (typeRes.code === 200) {
      carTypeDict.value = typeRes.data.map(item => ({
        label: item.dictLabel,
        value: parseInt(item.dictValue)
      }))
    }

    if (modelRes.code === 200) {
      carModelDict.value = modelRes.data.map(item => ({
        label: item.dictLabel,
        value: parseInt(item.dictValue)
      }))
    }
	
	if (modelRes.code === 200) {
	  sysVerification.value = modelRes.data.map(item => ({
	    label: item.dictLabel,
	    value: parseInt(item.dictValue)
	  }))
	}
	
  } catch (error) {
    console.error('字典加载失败:', error)
  }
}


// 工具函数
const formatTime = timestamp => {
  if (!timestamp) return '--'
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
}

const pad = n => n.toString().padStart(2, '0')

// 核销操作
const verifyPopup = ref()
let isVerifying = false

const loadOrderDetail = async () => {
  try {
    // 1. 加载订单基本信息
    const detailRes = await request({
      url: `/serviceItem/order/detail?orderId=${orderInfo.orderId}`,
      method: 'get'
    })

    if (detailRes.code === 200) {
      const data = detailRes.data
      Object.assign(orderInfo, {
        orderId: data.orderId,
        verificationCode: data.verificationCode,
        vehicle: data.vehicle || {},
        services: [
          ...(data.serviceItems || []).map(item => ({
            name: item.serviceName,
            price: item.actualAmount
          })),
          ...(data.servicePackages || []).map(pkg => ({
            name: pkg.packageName,
            price: pkg.actualAmount
          }))
        ],
        originalPrice: data.totalAmount,
        discount: data.totalAmount - data.actualAmount,
        paymentAmount: data.actualAmount,
        orderNumber: data.orderId.toString(),
        reserveTime: new Date(data.appointmentTime).getTime(),
        payTime: new Date(data.orderTime).getTime(),
        ext2: data.ext2
      })
      orderInfo.verificationStatus = orderInfo.ext2 === 1

      // 2. 如果已核销，加载核销记录
      if (orderInfo.verificationStatus) {
        const verificationRes = await request({
          url: `/serviceItem/verificationRecord?orderId=${orderInfo.orderId}`,
          method: 'get'
        })
        
        if (verificationRes.code === 200 && verificationRes.data) {
          // 使用接口返回的核销时间
          orderInfo.verifyTime = new Date(verificationRes.data.verificationTime).getTime()
        }
      }
    }
  } catch (error) {
    console.error('订单详情加载失败:', error)
  }
}

const handleVerification = () => {
  verifyPopup.value.open()
}

const confirmVerification = async () => {
  if (isVerifying) return
  isVerifying = true

  try {
    const res = await request({
      url: '/serviceItem/order/verify',
      method: 'post',
      data: { orderId: orderInfo.orderId },
      header: { 'Content-Type': 'application/json' }
    })

    if (res.code === 200) {
		orderInfo.verifyTime = res.data
		orderInfo.verificationStatus = true
		
      // 重新加载最新订单数据
      await loadOrderDetail()
      
      uni.showToast({
        title: '核销成功',
        icon: 'success',
        duration: 2000
      })
    }
  } catch (error) {
    uni.showToast({
      title: error.message || '核销失败，请重试',
      icon: 'none',
      duration: 2000
    })
  } finally {
    verifyPopup.value.close()
    isVerifying = false
  }
}

const cancelVerification = () => {
  verifyPopup.value.close()
}


onLoad(async (options) => {
  await loadDictData()
  orderInfo.orderId = options.id
  await loadOrderDetail()
})
</script>

<style lang="scss" scoped>
.page-container {
  padding: 32rpx;
  background: #f5f5f5;
  min-height: 120vh;
}

.section {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
}

.verification-section {
  text-align: center;
  
  .verification-code {
    margin-bottom: 32rpx;
    
    .code-text {
      display: block;
      font-size: 56rpx;
      color: #e4393c;
      font-weight: bold;
      letter-spacing: 8rpx;
    }
    
    .code-label {
      font-size: 24rpx;
      color: #999;
    }
  }
  
  .car-model {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    color: #666;
    
    .uni-icons {
      margin-right: 8rpx;
    }
  }
}

.service-section {
  .service-item {
    display: flex;
    justify-content: space-between;
    padding: 24rpx 0;
    border-bottom: 1rpx solid #eee;
    
    &:last-child {
      border-bottom: none;
    }
    
    .service-name {
      color: #333;
    }
    
    .service-price {
      color: #e4393c;
      font-weight: 500;
    }
  }
}

.info-section {
  .info-item {
    display: flex;
    justify-content: space-between;
    padding: 24rpx 0;
    font-size: 28rpx;
    color: #666;
    
    &.total {
      border-top: 2rpx solid #eee;
      padding-top: 32rpx;
      margin-top: 16rpx;
      font-weight: 500;
    }
    
    .discount {
      color: #52c41a;
    }
    
    .amount {
      color: #e4393c;
      font-size: 32rpx;
      font-weight: bold;
    }
    
    .order-id {
      color: #999;
      font-size: 24rpx;
    }
  }
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 24rpx 32rpx;
  box-shadow: 0 -4rpx 12rpx rgba(0,0,0,0.05);
  
  .verify-btn {
    background: #1890ff;
    color: #fff;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 44rpx;
    font-size: 32rpx;
    transition: all 0.3s;
    
    &.verified {
      background: #bae7ff;
      color: #1890ff;
    }
    
    &[disabled] {
      opacity: 0.6;
      background: #f5f5f5;
      color: #999;
    }
  }
}

.car-info {
  display: flex;
  align-items: center;
  gap: 16rpx;
  font-size: 28rpx;
  
  .license-plate {
    padding: 4rpx 12rpx;
    background: #f0f0f0;
    border-radius: 8rpx;
  }
}
</style>